package com.yohann.algorithm;

/**
 * <p>
 * 环形队列
 * </p>
 *
 * @author Yohann
 * @since 2020/9/22
 */
public class CircleArrayTest {
    public static void main(String[] args) {
        CircleArray arrayQueue = new CircleArray(4);

        try {
            arrayQueue.addQueue(1);
            arrayQueue.addQueue(2);
            arrayQueue.addQueue(3);
            System.out.println(arrayQueue.getQueue());
            System.out.println(arrayQueue.getQueue());
            System.out.println(arrayQueue.getQueue());
            arrayQueue.addQueue(4);
            arrayQueue.addQueue(5);
            arrayQueue.addQueue(6);
            arrayQueue.show();
            System.out.println(arrayQueue.getQueue());
            System.out.println(arrayQueue.getQueue());
            System.out.println(arrayQueue.getQueue());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

class CircleArray{
    //最大容量
    public int maxSize;
    //队列头部
    public int front;
    //队列尾部
    public int rear;
    //存储队列的数组
    public int[] arr;

    public CircleArray(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    public boolean isFull(){
        //队列头尾间隔一个maxSize
        return (rear+1) % maxSize == front;
    }

    public boolean isEmpty(){
        return rear == front;
    }

    public void addQueue(int num){
        //判断队列是否满
        if (isFull()){
            System.out.println("已满！");
            return;
        }

        arr[rear] = num;
        //超过尾部重新开始
        rear = (rear + 1) % maxSize;
    }

    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空！");
        }

        int temp = arr[front];
        //超过尾部重新开始
        front = (front + 1) % maxSize;

        System.out.println("******************");
        System.out.println("获取队列数据");
        return temp;
    }

    public void show(){
        if (isEmpty()){
            System.out.println("队列为空！");
            return;
        }

        System.out.println("******************");
        System.out.println("队列数据如下");
        //有效数据(rear-front)%maxSize
        for (int i = front; i < front + size(); i++) {
            System.out.println(arr[i%maxSize]);
        }
    }

    public int size(){
        //不加maxSize会出现负数
        return (rear -front + maxSize)%maxSize;
    }

    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空！");
        }

        return arr[front];
    }
}